import {HEARTBEAT_HOST_SCHOOL, HEARTBEAT_HOST_OUT} from '@/config/ip.js';

function Network(url, name, el){
  this.url = url;
  this.timer = null;
  this.isOnLine = true;
  this.eventName = 'networkStatus';
  this.beatTime = 3000;
  this.name = name;
  this.el = el;
}

Network.prototype.fireEvent = function(event, data) {
  let evt = new Event(event);
  evt.data = data;
  this.el.dispatchEvent(evt);
}

Network.prototype.detect = function(){
  let _this = this;
  let img = new Image();
  img.onload = function() {
    if(!_this.isOnLine) {
      _this.isOnLine = true;
      _this.fireEvent(_this.eventName, {
        name: _this.name,
        status: 'online',
        url: _this.url
      });
    }
    _this.timer = setTimeout(_this.detect.bind(_this), _this.beatTime);
  }
  img.onerror = function() {
    if(_this.isOnLine) {
      _this.isOnLine = false;
      _this.fireEvent(_this.eventName, {
        name: _this.name,
        status: 'offline',
        url: _this.url
      });
    }
    _this.timer = setTimeout(_this.detect.bind(_this), _this.beatTime);
  }
  img.src = this.url + '?t=' + (new Date()).getTime();
}

let url = '/heartbeat/heart.gif';
let schoolUrl = HEARTBEAT_HOST_SCHOOL + url;
let outUrl = HEARTBEAT_HOST_OUT + url;

// let schoolDetect = new Network(schoolUrl, 'schoolNetwork');
// schoolDetect.detect();

// let outDetect = new Network(outUrl, 'outNetwork');
// outDetect.detect();

// window.addEventListener('networkStatus', function(e){
//   console.log(e);
// })
let schoolDetect;
let outDetect;
export default function init(el){
  if(schoolDetect){
    clearTimeout(schoolDetect.timer);
  }else{
    schoolDetect = new Network(schoolUrl, 'schoolNetwork', el);
  }
  schoolDetect.detect();

  if(outDetect){
    clearTimeout(outDetect.timer);
  }else{
    outDetect = new Network(outUrl, 'outNetwork', el);
  }
  outDetect.detect();
}
